<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 基础表格 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-lx-add" class="handle-del mr10" @click="addNotice">发布公告</el-button>
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <!-- <el-select v-model="query.role" placeholder="角色" class="handle-select mr10">
                    <el-option key="1" label="学生" value="学生"></el-option>
                    <el-option key="2" label="老师" value="老师"></el-option>
                </el-select>-->
                <el-input v-model="query.title" placeholder="公告标题" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="handleReset">重置</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="title" label="公告标题" align="center"></el-table-column>
                <!-- <el-table-column prop="content" label="公告内容" align="center"></el-table-column> -->
                <el-table-column prop="createTime" label="发布时间" align="center"></el-table-column>
                <el-table-column prop="readNum" label="阅读次数" align="center"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <span>
                                <i class="el-icon-lx-more"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item
                                    ><el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button></el-dropdown-item
                                >
                                <el-dropdown-item
                                    ><el-button type="text" @click="toDetail(scope.$index, scope.row)"
                                        >查看详情</el-button
                                    ></el-dropdown-item
                                >
                                <el-dropdown-item
                                    ><el-button type="text" @click="handleDelete(scope.$index, scope.row)"
                                        >删除</el-button
                                    ></el-dropdown-item
                                >
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
            <!-- <div>
                <a-pagination
                    v-model="current"
                    :page-size-options="pageSizeOptions"
                    :total="total"
                    show-size-changer
                    :page-size="pageSize"
                    @showSizeChange="onShowSizeChange"
                >
                    <template slot="buildOptionText" slot-scope="props">
                        <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
                        <span v-if="props.value === '50'">全部</span>
                    </template>
                </a-pagination>
            </div> -->
        </div>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑公告" :visible.sync="isEditNoticeShow" width="70%">
            <el-form :model="form" ref="ruleForm" label-width="80px" class="demo-ruleForm">
                <el-form-item label="公告标题">
                    <el-input v-model="form.title" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="公告内容">
                    <quill-editor ref="myTextEditor" v-model="form.content" :options="editorOption"></quill-editor>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editNoticeCancel">取 消</el-button>
                <el-button type="primary" @click="editNoticeSave">保 存</el-button>
            </span>
        </el-dialog>
        <!-- 发布公告弹框 -->
        <el-dialog title="发布公告" :visible.sync="isAddNoticeShow" width="70%">
            <el-form :model="notice" ref="ruleForm" label-width="80px" class="demo-ruleForm">
                <el-form-item label="公告标题">
                    <el-input v-model="notice.title" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="公告内容">
                    <quill-editor ref="myTextEditor" v-model="notice.content" :options="editorOption"></quill-editor>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addNoticeCancel">取 消</el-button>
                <el-button type="primary" @click="addNoticeSave">发 布</el-button>
            </span>
        </el-dialog>
        <!-- 查看详情 -->
        <el-drawer :title="drawerTitle" :visible.sync="drawer" :direction="direction">
            <!-- <div v-html="form.content"></div> -->
            <div class="ql-container">
                <div class="ql-editor" v-html="form.content"></div>
            </div>
            <div class="drawerFoot">
                <p>{{ form.createTime }}</p>
                <p>阅读次数：{{ form.readNum }}次</p>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
import { fetchData } from '../../../api/index';
import { getNotice, setUser, removeNotice, createNotice, setNotice } from '@/views/api/api.js';
export default {
    name: 'noticeManagement',
    components: {
        quillEditor
    },
    data() {
        return {
            pageSizeOptions: ['10', '20', '30', '40', '50'],
            current: 1,
            pageSize: 10,
            total: 50,
            drawerTitle: '',
            drawer: false,
            direction: 'rtl',
            editorOption: {
                placeholder: '请输入公告内容'
            },
            query: {
                title: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            isAddNoticeShow: false,
            isEditNoticeShow: false,
            notice: {
                title: '',
                content: ''
            },
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            rules: {
                username: [{ required: true, message: '用户名不能为空！', trigger: 'blur' }],
                password: [{ required: true, message: '密码不能为空！', trigger: 'blur' }],
                phone: [{ required: true, message: '手机号码不能为空！', trigger: 'blur' }],
                college: [{ required: true, message: '学院不能为空！', trigger: 'blur' }],
                role: [{ required: true, message: '角色不能为空！', trigger: 'blur' }],
                sex: [{ required: true, message: '性别不能为空！', trigger: 'blur' }],
                status: [{ required: true, message: '审核状态不能为空！', trigger: 'blur' }],
                email: [{ required: true, message: '邮箱不能为空！', trigger: 'blur' }],
                safetyProblem1: [{ required: true, message: '安全问题1不能为空！', trigger: 'blur' }],
                safetyAnswer1: [{ required: true, message: '安全问题答案1不能为空！', trigger: 'blur' }],
                safetyProblem2: [{ required: true, message: '安全问题2不能为空！', trigger: 'blur' }],
                safetyAnswer2: [{ required: true, message: '安全问题答案2不能为空！', trigger: 'blur' }]
            }
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取所有的用户数据
        getData() {
            // fetchData(this.query).then(res => {
            //     console.log(res);
            //     this.tableData = res.list;
            //     this.pageTotal = res.pageTotal || 50;
            // });
            getNotice(this.query).then((res) => {
                if (!res.data.code) {
                    // 成功
                    this.tableData = res.data.Info;
                    this.pageTotal = res.data.total;
                    console.log(res);
                    for (let j = 0; j < this.tableData.length; j++) {
                        this.tableData[j].createTime = this.utc2beijing(this.tableData[j].createTime);
                    }
                } else {
                    // 失败
                    this.tableData = res.data.Info;
                    this.pageTotal = res.data.total;
                    this.$message({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            });
        },
        onShowSizeChange(current, pageSize) {
            this.pageSize = pageSize;
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 触发重置按钮
        handleReset() {
            this.query = {
                title: '',
                pageIndex: 1,
                pageSize: 10
            };
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.multipleSelection = [];
                    this.multipleSelection.push(row._id);
                    let params = {
                        multipleSelection: this.multipleSelection
                    };
                    removeNotice(params).then((res) => {
                        if (res.data.code) {
                            // Toast.fail(res.data.msg)
                        } else {
                            this.$message.success('删除成功');
                            this.getData();
                            this.multipleSelection = [];
                        }
                    });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = [];
            for (let i = 0; i < val.length; i++) {
                this.multipleSelection.push(val[i]._id);
            }
        },
        delAllSelection() {
            // 二次确认删除
            if (this.multipleSelection.length > 0) {
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        let params = {
                            multipleSelection: this.multipleSelection
                        };
                        removeNotice(params).then((res) => {
                            if (res.data.code) {
                                // Toast.fail(res.data.msg)
                            } else {
                                this.$message.success('删除成功');
                                this.getData();
                                this.multipleSelection = [];
                            }
                        });
                    })
                    .catch(() => {});
            } else {
                this.$message.warning('请选择要删除的用户');
            }
        },
        // 发布公告
        addNotice() {
            this.isAddNoticeShow = true;
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = JSON.parse(JSON.stringify(row));
            this.isEditNoticeShow = true;
        },
        // 查看详情操作
        toDetail(index, row) {
            this.drawer = true;
            this.form = JSON.parse(JSON.stringify(row));
            this.drawerTitle = this.form.title;
        },
        // 保存编辑
        saveEdit(form) {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let params = {
                        id: this.form._id,
                        password: this.form.password,
                        phone: this.form.phone,
                        college: this.form.college,
                        role: this.form.role,
                        sex: this.form.sex,
                        email: this.form.email,
                        safetyProblem1: this.form.safetyProblem1,
                        safetyProblem2: this.form.safetyProblem2,
                        safetyAnswer1: this.form.safetyAnswer1,
                        safetyAnswer2: this.form.safetyAnswer2
                    };
                    setUser(params).then((res) => {
                        if (res.data.code) {
                            this.$message({
                                showClose: true,
                                message: res.data.msg,
                                type: 'error'
                            });
                        } else {
                            this.editVisible = false;
                            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                            this.$set(this.tableData, this.idx, this.form);
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        cancelEdit(form) {
            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            console.log(val, this.query.pageIndex);
            this.getData();
        },
        scope(scope) {
            console.log(scope);
        },
        // 时间戳转为时间
        timestampToTime(timestamp) {
            var date = new Date(timestamp); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '年';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日 ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            return Y + M + D + h + m + s;
        },
        // UTC时间格式转通用格式时间
        // eslint-disable-next-line camelcase
        utc2beijing(utc_datetime) {
            // 转为正常的时间格式 年-月-日 时:分:秒
            // eslint-disable-next-line camelcase
            var T_pos = utc_datetime.indexOf('T');
            // eslint-disable-next-line camelcase
            var Z_pos = utc_datetime.indexOf('Z');
            // eslint-disable-next-line camelcase
            var year_month_day = utc_datetime.substr(0, T_pos);
            // eslint-disable-next-line camelcase
            var hour_minute_second = utc_datetime.substr(
                // eslint-disable-next-line camelcase
                T_pos + 1,
                // eslint-disable-next-line camelcase
                Z_pos - T_pos - 1
            );
            // eslint-disable-next-line camelcase
            var new_datetime = year_month_day + ' ' + hour_minute_second; // 2017-03-31 08:02:06

            // 处理成为时间戳
            // eslint-disable-next-line no-use-before-define
            timestamp = new Date(Date.parse(new_datetime));
            // eslint-disable-next-line no-use-before-define
            timestamp = timestamp.getTime();
            // eslint-disable-next-line no-use-before-define
            timestamp = timestamp / 1000;

            // 增加8个小时，北京时间比utc时间多八个时区
            // eslint-disable-next-line no-use-before-define
            var timestamp = timestamp + 8 * 60 * 60;

            // 时间戳转为时间
            // eslint-disable-next-line camelcase
            var beijing_datetime = this.timestampToTime(timestamp * 1000);
            // eslint-disable-next-line camelcase
            return beijing_datetime; // 2017-03-31 16:02:06
        },
        addNoticeCancel() {
            this.isAddNoticeShow = false;
        },
        addNoticeSave() {
            if (!this.notice.title) {
                this.$message.error(`标题不能为空`);
                return false;
            } else if (!this.notice.content) {
                this.$message.error(`内容不能为空`);
                return false;
            }
            let params = {
                title: this.notice.title,
                content: this.notice.content
            };
            createNotice(params).then((res) => {
                if (res.data.code) {
                } else {
                    this.isAddNoticeShow = false;
                    this.$message.success(`发布成功`);
                    this.getData();
                    this.notice = {
                        title: '',
                        content: ''
                    };
                }
            });
        },
        editNoticeCancel() {
            this.isEditNoticeShow = false;
        },
        editNoticeSave() {
            if (!this.form.title) {
                this.$message.error(`标题不能为空`);
                return false;
            } else if (!this.form.content) {
                this.$message.error(`内容不能为空`);
                return false;
            }
            let params = {
                id: this.form._id,
                title: this.form.title,
                content: this.form.content
            };
            setNotice(params).then((res) => {
                if (res.data.code) {
                } else {
                    this.isEditNoticeShow = false;
                    this.$message.success(`编辑成功`);
                    this.getData();
                    this.notice = {
                        title: '',
                        content: ''
                    };
                }
            });
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
/deep/ .el-drawer__body {
    padding: 20px;
}
/deep/ .el-drawer__body img {
    width: 100%;
}
.drawerFoot {
    color: #72767b;
    text-align: right;
    font-size: 14px;
    margin-top: 20px;
}
/deep/ .el-drawer__open .el-drawer.rtl {
    overflow-y: scroll;
}
</style>
